<template>
  <div class="base-station">
    <div class="m-h3-btn-box border margin-top30">
      <h3 class="fl">
        答题器基站管理
      </h3>
      <div class="u-btn-box">
        <el-button type="primary" @click="onAdd" size="small"
          >添加基站</el-button
        >
      </div>
    </div>
    <div class="base-station-search">
      <el-form label-width="80px" :model="searchParams" :inline="true">
        <el-form-item label="基站名称">
          <el-input
            v-model.trim="searchParams.name"
            @keyup.enter.native="onSearch"
            placeholder="请输入名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="SN码">
          <el-input
            v-model.trim="searchParams.sn"
            @keyup.enter.native="onSearch"
            placeholder="请输入SN码"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch" size="small"
            >搜索</el-button
          >
          <el-button type="primary" @click="onReset" size="small"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <div class="nice-table">
        <el-table :data="baseStationList" :border="true">
          <el-table-column type="index" label="序号" width="50">
          </el-table-column>
          <el-table-column prop="name" label="基站名称"></el-table-column>
          <el-table-column prop="sn" label="SN码"></el-table-column>
          <el-table-column prop="sn" label="绑定班级">
            <template slot-scope="scope">
              <template
                v-if="scope.row.classList && scope.row.classList.length"
              >
                <el-popover
                  v-if="scope.row.classList.length >= 2"
                  placement="top-start"
                  trigger="hover"
                >
                  <div v-if="scope.row.classList.length >= 2">
                    <div
                      v-for="(item, ind) in scope.row.classList"
                      :key="item.className + ind"
                    >
                      {{ item.className }}
                    </div>
                  </div>
                  <span slot="reference" v-html="handleClassName(scope.row.classList)"></span>
                </el-popover>
                <span v-else v-html="handleClassName(scope.row.classList)"></span>
              </template>
            </template>
          </el-table-column>
          <el-table-column
            prop="bindAmNum"
            label="配对答题器数量"
          ></el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="200"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button size="small" type="text" @click="onLook(scope.row)"
                >查看</el-button
              >
              <el-button size="small" type="text" @click="onBind(scope.row)"
                >绑定班级</el-button
              >
              <el-button size="small" type="text" @click="onEdit(scope.row)"
                >编辑</el-button
              >
              <el-button size="small" type="text" @click="onDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :current-page="pagination.pageNum"
          :page-size="pagination.pageSize"
          layout="total,sizes, prev, pager, next, jumper "
          :total="pagination.total || 0"
        ></el-pagination>
      </div>
    </div>
    <edit-base-station
      v-if="editDialog.visible"
      :dialogVisible="editDialog.visible"
      :schoolId="schoolId"
      :mode="editDialog.mode"
      :info="editDialog.info"
      @refresh="onRefreshList"
      @cancel="onCancelEdit"
    />
  </div>
</template>
<script>
import EditBaseStation from './edit-base-station';
import {
  getBaseStationList,
  deleteBaseStation,
  getBaseStationDetail,
} from '@/api/baseStation.js';
import { ERROR_CODE } from '@/api/api.js';

const dialogInit = {
  visible: false,
  mode: '',
  info: null,
};

export default {
  name: 'base-station',
  components: {
    EditBaseStation,
  },
  data() {
    return {
      searchParams: {
        name: '',
        sn: '',
      },
      schoolId: '',
      baseStationList: [],
      pagination: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
        handleCurrentChange: this.handleCurrentChange,
        handleSizeChange: this.handleSizeChange,
      },
      editDialog: {
        ...dialogInit,
      },
      // ^[\u4e00-\u9fa5a-zA-Z0-9()_-]*$
    };
  },
  activated() {
    this.schoolId = '';
    this.$nextTick(() => {
      this.schoolId = (this.$route.params.id || '').toString();
      this.searchParams = {
        name: '',
      };

      this.getList();
    });
  },
  methods: {
    async getList() {
      let res = await getBaseStationList({
        schoolId: this.schoolId,
        pageNum: this.pagination.pageNum,
        pageSize: this.pagination.pageSize,
        ...this.searchParams,
      });
      if (res[0]) {
        return;
      }
      let data = res[1];
      if (data && data.code === 0 && data.data) {
        const { totalPage, currPage, totalCount, list } = data.data;
        if (totalPage > 0 && totalPage < currPage) {
          this.handleCurrentChange(totalPage);
        } else {
          this.pagination.total = totalCount;
          this.baseStationList = list;
        }
      } else {
        this.$message.error(data.msg);
      }
    },
    handleClassName(classList) {
      if (!classList || !classList.length) {
        return '';
      }

      let classString = '';
      let classNames = [];
      classList.slice(0, 1).forEach((classItem) => {
        classNames.push(classItem.className);
      });

      classString = classNames.join('、').substr(0, 6);
      if (classList.length > 1) {
        classString = `${classString}等<span class="number">${classList.length}</span>个班级`;
      }
      return classString;
    },
    handleCurrentChange(val) {
      this.pagination.pageNum = val;
      this.getList();
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.getList();
    },
    onSearch() {
      this.pagination.pageNum = 1;
      this.getList();
    },
    onReset() {
      this.searchParams = {
        name: '',
      };
      this.getList();
    },
    closeEditDialog() {
      this.editDialog = {
        ...dialogInit,
      };
    },
    getDetail(row, callback) {
      getBaseStationDetail({
        schoolId: this.schoolId,
        baseStationId: row.baseStationId,
      }).then((res) => {
        let data = res[1];
        if (res[0]) {
          if (data.code === ERROR_CODE.REFRESH_LIST) {
            this.onRefreshList();
          }
          return;
        }
        if (!data.data) {
          return;
        }

        let info = row;
        if (data.data && data.code === 0) {
          info = data.data;
          if (callback) {
            callback(info);
          }
        }
      });
    },
    // 如果是编辑，则还是请求当前列表；新增才需要回到第一页
    onRefreshList(keepSearch) {
      this.closeEditDialog();
      if (!keepSearch) {
        this.pagination.pageNum = 1;
        this.onReset();
      } else {
        this.getList();
      }
    },
    onCancelEdit() {
      this.closeEditDialog();
    },
    onAdd() {
      this.editDialog = {
        visible: true,
        mode: 'add',
        info: null,
      };
    },
    onEdit(row) {
      this.getDetail(row, (info) => {
        this.editDialog = {
          visible: true,
          mode: 'edit',
          info: {
            ...info,
          },
        };
      });
    },
    onDelete(row) {
      if (row && row.classList && row.classList.length) {
        this.$confirm('请移除所有绑定班级后删除！', '提示', {
          confirmButtonText: '确定',
          type: 'warning',
        });
        return;
      }
      this.$confirm('确认删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          deleteBaseStation({
            schoolId: this.schoolId,
            baseStationId: row.baseStationId,
          }).then((res) => {
            let data = res[1];
            if (res[0]) {
              if (data.code === ERROR_CODE.REFRESH_LIST) {
                this.onRefreshList();
              }
              return;
            }
            if (data && data.code === 0) {
              this.$message.success('操作成功！');
              this.getList();
            }
          });
        })
        .catch((e) => {
          console.log('操作失败：', e);
        });
    },
    onBind(row) {
      this.getDetail(row, (info) => {
        this.$emit('bindTeach', info);
      });
    },
    onLook(row) {
      this.getDetail(row, (info) => {
        this.$router.push({
          name: 'base-station-detail',
          query: {
            schoolId: this.schoolId,
            id: info.baseStationId,
          },
        });
      });
    },
  },
};
</script>
<style scoped></style>
